#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<iostream>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>

//#define Port 8081
void Usage(std::string s)
{
  std::cout<<"Usage"<<"\n\t"<<s<<" prot"<<std::endl;
}
//服务端
int main(int argv, char* argc[])
{
  if(argv!=2)
  {
    Usage(argc[0]);
    return 1;
  }
  int sock=socket(AF_INET,SOCK_DGRAM,0);
  if(sock<0)
  {
    std::cerr<<"socket error"<<std::endl;
    return 1;
  }
  std::cout<<"socket "<<sock<<std::endl;
  //绑定端口号
  struct sockaddr_in local;
  memset(&local,0,sizeof(local));

  local.sin_family=AF_INET;
  local.sin_port=htons(atoi(argc[1]));                     //注意因为可以被获取，要成网络字节序
  local.sin_addr.s_addr=htonl(INADDR_ANY);       //INADDR_ANY可以bind此主机上所有ip
 if( bind(sock,(struct sockaddr*)&local,sizeof(local))<0)
 {
   std::cerr<<"bind error"<<std::endl;
   return 1;
 }
 //接收数据
 char message[1024];
 message[0]=0;
 while(1)
 {
   struct sockaddr_in peer;
   socklen_t len=sizeof(peer);

   ssize_t s=recvfrom(sock,message,sizeof(message)-1,0,(struct sockaddr*)&peer,&len);
   if(s>0)
   {
     //接收成功
     std::cout<<message<< " server"<<std::endl;
     FILE* in=popen(message,"r");
     if(in==nullptr)
     {
       continue;
     }
     std::string echo_message;
     char line[124];
     while(fgets(line,sizeof(line),in))
     {
       echo_message+=line;
     }
     //把结果返回回去
     if(sendto(sock,echo_message.c_str(),echo_message.size(),0,(struct sockaddr*)&peer,len)<0)
     {
       std::cerr<<"sendto error"<<std::endl;
     }
    // //进行程序替换，并把结果返回去，不能用dup2(sock,1)
    //if(fork()==0)
    //{

    //  char* comand[124];
    //  comand[0]=strtok(message," ");
    //  int i=1;
    //  while((comand[i]=strtok(NULL," "))!=NULL)     //到这时，会把comand最后添加NULL
    //  {
    //    i++;
    //  }

    //  //执行程序替换
    //  execvp(comand[0],comand);
    // }
   }
   else{
     //接收失败
     continue;
   }
 }
  return 0;
}
